<template>
  <div class="profile-container">
    <el-row :gutter="20">
      <!-- 左侧个人信息卡片 -->
      <el-col :span="8">
        <el-card class="profile-card">
          <div class="user-avatar">
            <el-avatar :size="100" :src="userInfo.avatar || require('@/assets/avatar-default.png')"></el-avatar>
            <el-upload class="avatar-uploader" action="#" :show-file-list="false" :before-upload="beforeAvatarUpload">
              <el-button size="small" type="primary">更换头像</el-button>
            </el-upload>
          </div>
          <h2>{{ userInfo.username }}</h2>
          <p class="user-role">
            {{ userInfo.userType === 'user' ? '普通用户' : '普通商家' }}
          </p>
          <div class="user-stats">
            <div class="stat-item">
              <span class="stat-value">{{ userInfo.orderCount }}</span>
              <span class="stat-label">{{ userInfo.userType === 'user' ? '订单数' : '已服务订单数' }}</span>
            </div>
            <div class="stat-item" v-if="userInfo.userType === 'user'">
              <span class="stat-value">{{ userInfo.petCount }}</span>
              <span class="stat-label">宠物数</span>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 右侧信息编辑区 -->
      <el-col :span="16">
        <el-card>
          <el-tabs v-model="activeTab">
            <!-- 基本信息 -->
            <el-tab-pane label="基本信息" name="basic">
              <el-form :model="userInfo" :rules="rules" ref="userForm" label-width="100px">
                <el-form-item label="用户名" prop="username">
                  <el-input v-model="userInfo.username"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="phone">
                  <el-input v-model="userInfo.phone"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                  <el-input v-model="userInfo.email"></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="updateUserInfo">保存修改</el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>

            <!-- 宠物信息 -->
            <el-tab-pane label="宠物信息" name="pets" v-if="userInfo.userType === 'user'">
              <div class="pets-list">
                <el-card v-for="pet in userInfo.pets" :key="pet.id" class="pet-card">
                  <div class="pet-info">
                    <el-avatar :size="60" :src="pet.avatar || require('@/assets/pet-default.png')"></el-avatar>
                    <div class="pet-details">
                      <h3>{{ pet.name }}</h3>
                      <p>{{ pet.breed }} | {{ pet.age }}岁</p>
                    </div>
                    <el-button type="text" @click="editPet(pet)">编辑</el-button>
                  </div>
                </el-card>
                <el-button type="primary" plain @click="addPet" class="add-pet-btn">
                  <i class="el-icon-plus"></i> 添加宠物
                </el-button>
              </div>
            </el-tab-pane>

            <!-- 安全设置 -->
            <el-tab-pane label="安全设置" name="security">
              <el-form :model="securityForm" :rules="securityRules" ref="securityForm" label-width="100px">
                <el-form-item label="原密码" prop="oldPassword">
                  <el-input type="password" v-model="securityForm.oldPassword" show-password></el-input>
                </el-form-item>
                <el-form-item label="新密码" prop="newPassword">
                  <el-input type="password" v-model="securityForm.newPassword" show-password></el-input>
                </el-form-item>
                <el-form-item label="确认密码" prop="confirmPassword">
                  <el-input type="password" v-model="securityForm.confirmPassword" show-password></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="updatePassword">修改密码</el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </el-col>
    </el-row>

    <!-- 宠物编辑对话框 -->
    <el-dialog :title="petDialogTitle" :visible.sync="petDialogVisible" v-if="userInfo.userType === 'user'">
      <el-form :model="petForm" :rules="petRules" ref="petForm" label-width="100px">
        <el-form-item label="宠物名称" prop="name">
          <el-input v-model="petForm.name"></el-input>
        </el-form-item>
        <el-form-item label="宠物类型" prop="type">
          <el-select v-model="petForm.type" placeholder="请选择宠物类型">
            <el-option label="狗狗" value="dog"></el-option>
            <el-option label="猫咪" value="cat"></el-option>
            <el-option label="其他" value="other"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="宠物品种" prop="breed">
          <el-input v-model="petForm.breed"></el-input>
        </el-form-item>
        <el-form-item label="宠物年龄" prop="age">
          <el-input-number v-model="petForm.age" :min="0" :max="30"></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="petDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="savePet">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'ProfilePage',
  data() {
    // 密码确认验证
    const validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.securityForm.newPassword) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      activeTab: 'basic',
      userInfo: {
        username: '',
        phone: '',
        email: '',
        avatar: '',
        orderCount: 0,
        petCount: 0,
        pets: []
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ]
      },
      securityForm: {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      securityRules: {
        oldPassword: [
          { required: true, message: '请输入原密码', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请再次输入密码', trigger: 'blur' },
          { validator: validatePass2, trigger: 'blur' }
        ]
      },
      petDialogVisible: false,
      petDialogTitle: '添加宠物',
      petForm: {
        name: '',
        type: '',
        breed: '',
        age: 0
      },
      petRules: {
        name: [
          { required: true, message: '请输入宠物名称', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择宠物类型', trigger: 'change' }
        ],
        breed: [
          { required: true, message: '请输入宠物品种', trigger: 'blur' }
        ],
        age: [
          { required: true, message: '请输入宠物年龄', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    // 从离线存储中获取最新用户信息
    this.loadUserInfo();
    // 监听登录状态变化
    this.emitter.on('login-status-changed', this.loadUserInfo);
  },
  beforeUnmount() {
    // 移除事件监听
    this.emitter.off('login-status-changed', this.loadUserInfo);
  },
  methods: {
    loadUserInfo() {
  // 从 localStorage 中获取当前登录用户
  const currentUser = JSON.parse(localStorage.getItem('currentUser'));

  if (currentUser) {
    // 从 localStorage 中获取用户和商家信息
    const users = JSON.parse(localStorage.getItem('users') || '[]');
    const merchants = JSON.parse(localStorage.getItem('merchants') || '[]');

    // 合并用户和商家信息
    const allUsers = [...users, ...merchants];

    // 根据当前登录用户的 username 查找对应的用户信息
    const user = allUsers.find(u => u.username === currentUser.username);

    if (user) {
      // 更新个人中心内容
      this.userInfo = {
        ...user,
        orderCount: user.orderCount || 0,
        petCount: user.pets ? user.pets.length : 0,
        userType: user.userType // 确保 userType 被正确设置
      };
    } else {
      this.$message.error('用户信息未找到');
    }
  } else {
    this.$message.error('未检测到登录用户');
  }
},
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    updateUserInfo() {
    this.$refs.userForm.validate((valid) => {
      if (valid) {
        // 从 localStorage 中获取用户和商家信息
        const users = JSON.parse(localStorage.getItem('users') || '[]');
        const merchants = JSON.parse(localStorage.getItem('merchants') || '[]');

        // 合并用户和商家信息
        const allUsers = [...users, ...merchants];

        // 找到当前用户
        const index = allUsers.findIndex(user => user.username === this.userInfo.username);

        if (index !== -1) {
          // 更新用户信息
          allUsers[index] = { ...this.userInfo };

          // 根据用户类型更新 localStorage
          if (this.userInfo.userType === 'user') {
            localStorage.setItem('users', JSON.stringify(allUsers.filter(user => user.userType === 'user')));
          } else {
            localStorage.setItem('merchants', JSON.stringify(allUsers.filter(user => user.userType === 'merchant')));
          }

          this.$message.success('个人信息更新成功');
        } else {
          this.$message.error('用户信息未找到');
        }
      }
    });
  },
    updatePassword() {
      this.$refs.securityForm.validate((valid) => {
        if (valid) {
          // 这里添加修改密码的逻辑
          this.$message.success('密码修改成功')
          this.securityForm = {
            oldPassword: '',
            newPassword: '',
            confirmPassword: ''
          }
        }
      })
    },
    addPet() {
      this.petDialogTitle = '添加宠物'
      this.petForm = {
        name: '',
        type: '',
        breed: '',
        age: 0
      }
      this.petDialogVisible = true
    },
    editPet(pet) {
      this.petDialogTitle = '编辑宠物信息'
      this.petForm = { ...pet }
      this.petDialogVisible = true
    },
    savePet() {
      this.$refs.petForm.validate((valid) => {
        if (valid) {
          // 更新宠物信息
          if (this.petForm.id) {
            // 更新现有宠物
            const index = this.userInfo.pets.findIndex(p => p.id === this.petForm.id);
            this.userInfo.pets[index] = { ...this.petForm };
          } else {
            // 添加新宠物
            this.userInfo.pets.push({
              ...this.petForm,
              id: Date.now()
            });
          }

          // 更新用户信息到 localStorage
          this.updateUserInfo();

          this.petDialogVisible = false;
          this.$message.success('宠物信息保存成功');
        }
      });
    }
  }
}
</script>

<style scoped>
.profile-container {
  max-width: 1200px;
  margin: 0 auto;
  padding-top: 64px;
}

.profile-card {
  text-align: center;
  padding: 20px;
}

.user-avatar {
  margin-bottom: 20px;
}

.avatar-uploader {
  margin-top: 10px;
}

.user-role {
  color: #666;
  margin: 10px 0;
}

.user-stats {
  display: flex;
  justify-content: space-around;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.stat-item {
  text-align: center;
}

.stat-value {
  display: block;
  font-size: 24px;
  color: #409EFF;
  font-weight: bold;
}

.stat-label {
  color: #666;
  font-size: 14px;
}

.pets-list {
  display: grid;
  gap: 20px;
}

.pet-card {
  margin-bottom: 10px;
}

.pet-info {
  display: flex;
  align-items: center;
  gap: 20px;
}

.pet-details {
  flex: 1;
}

.pet-details h3 {
  margin: 0 0 5px;
}

.pet-details p {
  margin: 0;
  color: #666;
}

.add-pet-btn {
  width: 100%;
  margin-top: 10px;
}

.el-form {
  max-width: 500px;
}
</style>